package com.cskaoyan.order.mq.delay;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;

/**
 * @author LY
 * @since 2022/06/21 21:11
 */
@Slf4j
@Component
public class DelayOrderCancelProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init(){
        // 1. 创建用于发送消息的producer对象
        producer = new DefaultMQProducer("delay_order_cancel_producer");
        // 2. 设置nameserver地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        // 3. 启动producer
        try {
            producer.start();
        } catch (MQClientException e) {
            log.info("DelayOrderCancelProducer启动失败！");
            e.printStackTrace();
        }
    }

    public boolean sendDelayOrderCancelMessage(String orderId){
        // 添加日志
        log.info("before send delay message {}", orderId);
        // 创建Message对象
        Message message = new Message();
        // 设置Topic名字
        message.setTopic("delay_order_cancel");
        // 添加消息数据
        byte[] body = orderId.getBytes(Charset.forName("utf-8"));
        message.setBody(body);
        // 设置延迟级别
        message.setDelayTimeLevel(4);
        // 开始发送消息
        log.info("start send delay message {}", orderId);
        SendResult send = null;
        try {
            send = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(send != null && SendStatus.SEND_OK.equals(send.getSendStatus())){
            // 发送成功
            log.info("success send delay message {}", orderId);
            return true;
        }
        // 发送失败
        log.info("error send delay message {}", orderId);
        return false;
    }
}
